class DataManager {
    constructor() {
        // 定义固定目标值用于控制打印
        const TARGET_PRINT_FLAG = '202508161606';
        const currentPrintFlag = localStorage.getItem('printLogFlag');

        // 非目标值/空则执行打印并更新标记
        if (currentPrintFlag !== TARGET_PRINT_FLAG) {
            localStorage.removeItem('chargeData');
            localStorage.removeItem('lastClearDate');
            localStorage.removeItem('previousDayData');
            localStorage.removeItem('withdrawalRecords');
            localStorage.removeItem('chargingCache');
            localStorage.removeItem('five');
            console.log('chargeData:', localStorage.getItem('chargeData'));
            console.log('lastClearDate:', localStorage.getItem('lastClearDate'));
            console.log('previousDayData:', localStorage.getItem('previousDayData'));
            console.log('withdrawalRecords:', localStorage.getItem('withdrawalRecords'));
            console.log('chargingCache:', localStorage.getItem('chargingCache'));
            console.log('chargingCache:', localStorage.getItem('five'));
            localStorage.setItem('printLogFlag', TARGET_PRINT_FLAG);
            console.log(`✅ 已执行打印，存储值已更新为「${TARGET_PRINT_FLAG}」`);
        }

        console.log('===== 数据管理器初始化 =====');
        this.handleDailyDataMigration();

        const stored = localStorage.getItem('chargeData');
        this.data = stored ? JSON.parse(stored) : this.generateInitialData();

        // ===== 核心新增：对比最后更新时间，不一致则执行 nowDate =====
        this.checkAndUpdateData();

        localStorage.setItem('chargeData', JSON.stringify(this.data));

        console.log('今日初始化数据：', {
            今日目标耗电量: this.data.todayFinalPower,
            今日最终用户数: this.data.todayFinalUsers,
            当前时间进度: `${(this.getDayProgress() * 100).toFixed(1)}%`,
            当前时段耗电量占比: `${(this.getPowerRatioByTime() * 100).toFixed(1)}%`,
            今日当前耗电量: this.data.power,
            今日当前用户数: this.data.users,
            今日初始总收益: this.data.totalIncome
        });

        window.addEventListener('storage', (e) => {
            if (e.key === 'chargeData') {
                const newData = JSON.parse(e.newValue);
                // 监听storage变化时，也对比更新时间
                if (newData.lastUpdate !== this.data.lastUpdate) {
                    this.data = newData;
                    this.nowDate(); // 数据变化则刷新
                    this.onUpdate?.(this.data);
                }
            }
        });

        this.timer = setInterval(() => {
            // 定时任务中也触发时间检查
            this.checkAndUpdateData();
        }, 1800000); // 30分钟 = 30×60×1000 = 1800000毫秒
        console.log('已启动定时任务，每30分钟刷新一次当前数据');
    }

    // ===== 新增：检查最后更新时间，不一致则执行 nowDate =====
    checkAndUpdateData() {
        // 1. 处理首次初始化：如果 data 不存在或 lastUpdate 未定义，直接执行 nowDate
        if (!this.data || this.data.lastUpdate === undefined) {
            console.log('🔵 首次初始化或数据异常，执行 nowDate 初始化数据');
            this.nowDate();
            return;
        }

        // 2. 获取当前数据的最后更新时间（毫秒级时间戳）
        const currentLastUpdate = this.data.lastUpdate;
        // 3. 计算当前时间与最后更新时间的差值（单位：分钟）
        const timeDiff = (new Date().getTime() - currentLastUpdate) / (1000 * 60);

        // 4. 规则：若差值>5分钟（可调整），执行 nowDate 刷新数据
        const EXPIRE_MINUTES = 5;
        if (timeDiff > EXPIRE_MINUTES || localStorage.getItem('printLogFlag')) {
            console.log(`⌛ 数据已过期（${timeDiff.toFixed(1)}分钟未更新），执行数据刷新`);
            this.nowDate();
        } else {
            console.log(`✅ 数据未过期（${timeDiff.toFixed(1)}分钟前更新），无需刷新`);
        }
    }

    // 生成初始数据（优化首次使用时的昨日数据为纯随机，新增订单数最小1限制）
    generateInitialData() {
        const lastMigrationDate = localStorage.getItem('lastMigrationDate');
        const previousDayData = localStorage.getItem('previousDayData');
        let oldpower, oldusers, oldorders, oldshouyi;

        // 处理昨日数据：首次使用/数据异常均随机生成（保持范围一致）
        if (!lastMigrationDate || !previousDayData) {
            // 首次使用浏览器 或 历史数据缺失/异常：完全随机生成昨日数据
            // 随机范围：992.06-2777.77（与今日数据范围一致）
            oldpower = +(Math.random() * (2777.77 - 992.06) + 992.06).toFixed(2);
            // 严格遵循“用户数=耗电量÷58取整”规则，且用户数最小为1（订单数=用户数，间接保证订单最小1）
            oldusers = Math.max(1, Math.round(oldpower / 58));
            oldorders = oldusers; // 订单数=用户数（同步最小1限制）
            oldshouyi = +(oldpower * 0.72 * 0.7).toFixed(2); // 收益计算规则与今日一致

            // 区分场景日志（便于调试）
            if (!lastMigrationDate && !previousDayData) {
                console.log('🔵 首次使用浏览器，随机生成昨日数据：', {
                    昨日耗电量: oldpower,
                    昨日用户数: oldusers,
                    昨日订单数: oldorders
                });
            } else {
                console.log('🟡 历史数据异常，随机生成昨日数据：', {
                    昨日耗电量: oldpower,
                    昨日用户数: oldusers,
                    昨日订单数: oldorders
                });
            }
        } else {
            // 有正常历史数据：读取归档数据
            try {
                const prevData = JSON.parse(previousDayData);
                oldpower = prevData.power || 0;
                oldusers = prevData.users || 0;
                oldorders = prevData.orders || 0;
                oldshouyi = prevData.dailyIncome || 0;

                // 基础校验：确保数据在合理范围（超出则重置为随机值）
                const minPower = 992.06;
                const maxPower = 2777.77;
                if (oldpower < minPower || oldpower > maxPower) {
                    oldpower = +(Math.random() * (maxPower - minPower) + minPower).toFixed(2);
                    oldusers = Math.max(1, Math.round(oldpower / 58)); // 用户数最小1
                    oldorders = oldusers; // 订单数同步最小1
                    oldshouyi = +(oldpower * 0.72 * 0.7).toFixed(2);
                    console.log('🟠 昨日数据超出范围，已重置为随机值：', { oldpower, oldusers, oldorders });
                } else {
                    // 即使数据在范围，仍强制用户数/订单数最小1
                    oldusers = Math.max(1, oldusers);
                    oldorders = Math.max(1, oldorders);
                }
            } catch (e) {
                // 解析异常时：随机生成兜底（强制用户数/订单数最小1）
                oldpower = +(Math.random() * (2777.77 - 992.06) + 992.06).toFixed(2);
                oldusers = Math.max(1, Math.round(oldpower / 58));
                oldorders = oldusers;
                oldshouyi = +(oldpower * 0.72 * 0.7).toFixed(2);
                console.log('🟠 昨日数据解析失败，随机生成兜底数据：', { oldpower, oldusers, oldorders });
            }
        }

        // 今日数据生成逻辑（新增订单数最小1限制）
        const todayFinalPower = +(Math.random() * (2777.77 - 992.06) + 992.06).toFixed(2);
        // 今日最终用户数：最小1（订单数=用户数，间接保证最终订单最小1）
        const todayFinalUsers = Math.max(1, Math.round(todayFinalPower / 58));
        const baseIncome = +(Math.random() * 20000 + 5000).toFixed(2);
        const chushitotalIncome = +(baseIncome - todayFinalPower).toFixed(2);
        console.log('初始收益值', chushitotalIncome);
        const powerRatio = this.getPowerRatioByTime();
        const power = +(todayFinalPower * powerRatio).toFixed(2);
        // 当前用户数：最小1（订单数=用户数，间接保证当前订单最小1）
        const users = Math.max(1, Math.round(power / 58));

        return {
            todayFinalPower,
            todayFinalUsers,
            power,
            users,
            orders: users, // 订单数=用户数（同步最小1限制）
            dailyIncome: +(power * 0.72 * 0.7).toFixed(2),
            oldpower,
            oldusers,
            oldorders,
            oldshouyi,
            totalIncome: chushitotalIncome,
            dailyElectricity: power,
            dailyCharge: +(power * 1.1).toFixed(2),
            dailyElectricityFee: +(power * 0.38).toFixed(2),
            dailyServiceFee: +(power * 0.72).toFixed(2),
            chargeUsers: users,
            withdrawableAmount: 35746.35,
            deviceCount: 10,
            onlineCount: 10,
            lastUpdate: new Date().getTime(),
            chushitotalIncome
        };
    }

    handleDailyDataMigration() {
        const lastMigrationDate = localStorage.getItem('lastMigrationDate');
        const today = new Date().toDateString();

        if (!lastMigrationDate || lastMigrationDate !== today) {
            const yesterdayData = localStorage.getItem('chargeData');
            try {
                const parsed = yesterdayData ? JSON.parse(yesterdayData) : {};
                // 迁移时强制昨日订单数/用户数最小1
                const migratedUsers = Math.max(1, parsed.todayFinalUsers || 0);
                const migratedOrders = Math.max(1, parsed.orders || 0);
                localStorage.setItem('previousDayData', JSON.stringify({
                    power: parsed.todayFinalPower || 0,
                    users: migratedUsers,
                    orders: migratedOrders,
                    dailyIncome: parsed.dailyIncome || 0
                }));
            } catch (e) {
                // 异常时兜底数据也强制最小1
                localStorage.setItem('previousDayData', JSON.stringify({
                    power: 0,
                    users: 1,
                    orders: 1,
                    dailyIncome: 0
                }));
            }

            localStorage.removeItem('chargeData');
            localStorage.setItem('lastMigrationDate', today);
        }
    }

    getDayProgress() {
        const now = new Date();
        const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const millisecondsPassed = now - startOfDay;
        const totalMillisecondsInDay = 24 * 60 * 60 * 1000;
        return Math.min(1, millisecondsPassed / totalMillisecondsInDay);
    }

    getPowerRatioByTime() {
        const now = new Date();
        const hour = now.getHours();
        const minute = now.getMinutes();
        const second = now.getSeconds();
        const totalMinutesNow = hour * 60 + minute + second / 60;

        if (hour < 10) return Math.min(0.35, (totalMinutesNow / 600) * 0.35);
        if (hour >= 10 && hour < 14) {
            const segmentProgress = (totalMinutesNow - 600) / 240;
            return 0.35 + Math.min(1, segmentProgress) * 0.35;
        }
        const segmentProgress = (totalMinutesNow - 840) / 600;
        return 0.7 + Math.min(1, segmentProgress) * 0.3;
    }

    nowDate() {
        const powerRatio = this.getPowerRatioByTime();
        const power = +(this.data.todayFinalPower * powerRatio).toFixed(2);
        // 刷新时强制当前用户数最小1（订单数=用户数，同步最小1）
        const users = Math.max(1, Math.round(power / 58));
        const dailyIncome = +(power * 0.72 * 0.7).toFixed(2);
        const newZongshouyi = +(this.data.chushitotalIncome + dailyIncome).toFixed(2);

        this.data = {
            ...this.data,
            power,
            users,
            orders: users, // 订单数=用户数（同步最小1限制）
            dailyIncome,
            totalIncome: newZongshouyi,
            dailyElectricity: power,
            dailyCharge: +(power * 1.1).toFixed(2),
            dailyElectricityFee: +(power * 0.38).toFixed(2),
            dailyServiceFee: +(power * 0.72).toFixed(2),
            chargeUsers: users,
            lastUpdate: new Date().getTime()
        };

        localStorage.setItem('chargeData', JSON.stringify(this.data));

        if (new Date().getSeconds() % 10 === 0) {
            console.log('数据刷新：', {
                当前时间: new Date().toLocaleTimeString(),
                当前时段耗电量占比: `${(powerRatio * 100).toFixed(1)}%`,
                今日最终用户数: this.data.todayFinalUsers,
                当前用户数: users,
                今日最终耗电量: this.data.todayFinalPower,
                当前耗电量: power,
                当前总收益: newZongshouyi,
                当前订单数: this.data.orders // 日志中新增订单数，便于验证
            });
        }

        this.onUpdate?.(this.data);
    }

    //更改设备数方法
    handleDataByDeviceCount() {
        const currentData = this.data;
        // 目标字段和整数字段定义（与之前一致）
        const targetFields = ['todayFinalPower', 'todayFinalUsers', 'power', 'users', 'orders', 'dailyIncome', 'oldpower', 'oldusers', 'oldorders', 'oldshouyi', 'totalIncome', 'chushitotalIncome', 'dailyElectricity', 'dailyCharge', 'dailyElectricityFee', 'dailyServiceFee', 'chargeUsers', 'withdrawableAmount', 'deviceCount', 'onlineCount'];
        const integerFields = ['todayFinalUsers', 'users', 'orders', 'oldusers', 'oldorders', 'chargeUsers', 'deviceCount', 'onlineCount'];

        // 关键判断：根据当前设备数决定操作类型
        const isDeviceCount5 = currentData.deviceCount === 5;
        const operation = isDeviceCount5 ? '乘以2' : '除以2';

        // 遍历字段执行对应操作，同时强制订单数/用户数最小1
        targetFields.forEach(field => {
            if (currentData[field] === undefined) return;
            const val = Number(currentData[field]);
            if (isNaN(val)) return;

            // 计算新值
            let newValue = isDeviceCount5
                ? (integerFields.includes(field) ? Math.round(val * 2) : +(val * 2).toFixed(2)) // 设备数为5时乘2
                : (integerFields.includes(field) ? Math.round(val / 2) : +(val / 2).toFixed(2)); // 设备数为10时除2

            // 对用户数、订单数强制最小1（即使计算后小于1，也重置为1）
            if (['todayFinalUsers', 'users', 'orders', 'oldusers', 'oldorders', 'chargeUsers'].includes(field)) {
                newValue = Math.max(1, newValue);
            }

            currentData[field] = newValue;
        });

        // 特殊处理：确保设备数和在线数严格同步（5↔10）
        currentData.deviceCount = isDeviceCount5 ? 10 : 5;
        currentData.onlineCount = currentData.deviceCount;

        // 保存更新
        this.data = currentData;
        localStorage.setItem('chargeData', JSON.stringify(currentData));
        this.onUpdate?.(this.data);

        console.log(JSON.parse(localStorage.getItem('chargeData') || '{}').deviceCount);        console.log(`✅ 设备数为${isDeviceCount5 ? 5 : 10}，已执行数据${operation}，当前订单数：${currentData.orders}`);
    }

    getSharedData() { return this.data; }
    onDataUpdate(callback) { this.onUpdate = callback; }
    destroy() {
        clearInterval(this.timer);
        console.log('已停止定时任务');
    }
}

window.dataManager = new DataManager();